from hashlib import md5
from django.shortcuts import render, redirect
from app01 import models
from django import forms
import logging


# Create your views here.

# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


# 使用modelform类优化代码
class UserForm(forms.ModelForm):
    class Meta:
        model_user = models.User
        fields = ['login', 'name', 'password', 'age', 'sex', 'email', 'role']


def user_list(request):
    """ 用户列表 """
    user_queryset = models.User.objects.all()
    for user in user_queryset:
        user.roles = ', '.join([role.role_name for role in user.role.all()]) if user.role.exists() else ""
    return render(request, "user_list.html", {"user_queryset": user_queryset})


def user_add(request):
    """ 添加用户 """
    if request.method == "GET":
        return render(request, "user_add.html")
    else:
        # 获取用户提交的数据
        login = request.POST.get("login_account")
        name = request.POST.get("user_name")
        password = request.POST.get("password")
        age = request.POST.get("age")
        sex = request.POST.get("sex")
        email = request.POST.get("email")
        models.User.objects.create(login=login, name=name, password=password, age=age, sex=sex, email=email)  # 保存到数据库
        return redirect("/user/list")


def user_delete(request):
    """ 删除用户 """
    nid = request.GET.get("nid")  # 获取ID
    models.User.objects.filter(id=nid).delete()  # 删除
    return redirect("/user/list")


def user_edit(request, nid):
    """ 修改用户信息 """
    if request.method == "GET":
        row_object = models.User.objects.filter(id=nid).first()  # 根据nid获取数据
        return render(request, "user_edit.html", {"row_object": row_object})
    else:
        # 获取用户提交的数据
        login = request.POST.get("login_account")
        name = request.POST.get("user_name")
        password = request.POST.get("password")
        age = request.POST.get("age")
        sex = request.POST.get("sex")
        email = request.POST.get("email")
        models.User.objects.filter(id=nid).update(login=login, name=name, password=password, age=age, sex=sex,
                                                  email=email)
        return redirect("/user/list")


def role_list(request):
    """ 角色列表 """
    role_queryset = models.Role.objects.all()
    for role in role_queryset:
        role.labels = ', '.join([label.label_name for label in role.label.all()]) if role.label.exists() else ""
    return render(request, "role_list.html", {"role_queryset": role_queryset})


def role_add(request):
    """ 添加角色 """
    if request.method == "GET":
        return render(request, "role_add.html")
    else:
        # 获取用户提交的数据
        role_name = request.POST.get("role_name")
        models.Role.objects.create(role_name=role_name)  # 保存到数据库
        return redirect("/role/list")


def role_delete(request):
    """ 删除角色 """
    nid = request.GET.get("nid")  # 获取ID
    models.Role.objects.filter(id=nid).delete()  # 删除
    return redirect("/role/list")


def role_edit(request, nid):
    """ 修改角色信息 """
    if request.method == "GET":
        row_object = models.Role.objects.filter(id=nid).first()  # 根据nid获取数据
        return render(request, "role_edit.html", {"row_object": row_object})
    else:
        # 获取用户提交的数据
        role_name = request.POST.get("role_name")
        models.Role.objects.filter(id=nid).update(role_name=role_name)  # 保存到数据库
        return redirect("/role/list")


def label_list(request):
    """ 菜单列表 """
    label_queryset = models.Label.objects.all()

    return render(request, "label_list.html", {"label_queryset": label_queryset})


def label_add(request):
    """ 添加菜单 """
    if request.method == "GET":
        return render(request, "label_add.html")
    else:
        # 获取用户提交的数据
        label_name = request.POST.get("label_name")
        previous_label = request.POST.get("previous_label")
        models.Label.objects.create(label_name=label_name, previous_label=previous_label)  # 保存到数据库
        return redirect("/label/list")


def label_delete(request):
    """ 删除菜单 """
    nid = request.GET.get("nid")  # 获取ID
    models.Label.objects.filter(id=nid).delete()  # 删除
    return redirect("/label/list")


def label_edit(request, nid):
    """ 修改菜单信息 """
    if request.method == "GET":
        row_object = models.Label.objects.filter(id=nid).first()  # 根据nid获取数据
        return render(request, "label_edit.html", {"row_object": row_object})
    else:
        # 获取用户提交的数据
        label_name = request.POST.get("label_name")
        previous_label = request.POST.get("previous_label")
        models.Label.objects.filter(id=nid).update(label_name=label_name, previous_label=previous_label)  # 保存到数据库
        return redirect("/label/list")


def user_role(request, nid):
    """ 给用户分配角色 """
    if request.method == "GET":
        context = {
            "role_choice": models.Role.objects.all(),
            "row_object": models.User.objects.filter(id=nid).first(),
            "selected_role_ids": set(models.User.objects.filter(id=nid).first().role.values_list('id', flat=True))
        }
        return render(request, "user_role.html", context)
    else:
        role_ids = request.POST.getlist("roles")
        user = models.User.objects.filter(id=nid).first()
        user.role.set(role_ids)  # 使用 set() 方法替换 clear() 和 add() 组合
        return redirect("/user/list")


PERMISSION_RELATIONS = {
    "user/list/": ["user/add/", "user/delete/", "user/<int:nid>/edit/"],
    "role/list/": ["role/add/", "role/delete/", "role/<int:nid>/edit/"],
    "label/list/": ["label/add/", "label/delete/", "label/<int:nid>/edit/"],
}


def role_label(request, nid):
    """ 给角色分配菜单 """
    if request.method == "GET":
        context = {
            "label_choice": models.Label.objects.all(),
            "row_object": models.Role.objects.filter(id=nid).first(),
            "selected_label_ids": set(models.Role.objects.filter(id=nid).first().label.values_list('id', flat=True))
        }
        return render(request, "role_label.html", context)
    else:
        label_ids = request.POST.getlist("labels")
        role = models.Role.objects.filter(id=nid).first()

        # 添加关联权限
        extended_label_ids = set(label_ids)
        for label_id in label_ids:
            label = models.Label.objects.get(id=label_id)
            main_permission = label.url
            if main_permission in PERMISSION_RELATIONS:
                related_labels = models.Label.objects.filter(url__in=PERMISSION_RELATIONS[main_permission])
                extended_label_ids.update(related_labels.values_list('id', flat=True))

        role.label.set(extended_label_ids)
        logger.info(f"Role {role.role_name} assigned labels: {extended_label_ids}")
        return redirect("/role/list")


class LoginForm(forms.Form):
    admin_login = forms.CharField(label="登录账号")
    pwd = forms.CharField(label="密码", widget=forms.PasswordInput)
    user_type = forms.ChoiceField(choices=[('user', '普通用户'), ('admin', '管理')], label="用户类型")

    def clean_password(self):
        pwd = self.cleaned_data.get("pwd")
        return md5(pwd)


def login(request):
    """ 登录 """
    if request.method == "GET":
        form = LoginForm()
        return render(request, 'login.html', {'form': form})
    else:
        form = LoginForm(data=request.POST)
        if form.is_valid():
            admin_login = form.cleaned_data['admin_login']
            pwd = form.cleaned_data['pwd']
            user_type = form.cleaned_data['user_type']

            if user_type == 'admin':
                admin_object = models.Admin.objects.filter(admin_login=admin_login, pwd=pwd).first()
                if admin_object:
                    request.session["info"] = {'id': admin_object.id, 'login': admin_object.admin_login,
                                               'name': admin_object.admin_name, "role": "admin"}
                    return redirect('/user/list')  # 管理员成功登录后跳转的页面
                else:
                    form.add_error("pwd", "账号或密码错误")
            elif user_type == 'user':
                user_object = models.User.objects.filter(login=admin_login, password=pwd).first()
                if user_object:
                    request.session["info"] = {'id': user_object.id, 'login': user_object.login,
                                               'name': user_object.name, "role": "user"}
                    return redirect('/main/')  # 普通用户成功登录后跳转的页面
                else:
                    form.add_error("pwd", "账号或密码错误")

        return render(request, 'login.html', {'form': form})


def logout(request):
    """ 注销 """
    request.session.clear()
    return redirect('/login/')


def type(request):
    """ 借书 """
    return render(request, 'type.html')


def process(request):
    """ 还书 """
    return render(request, 'process.html')


def params(request):
    """ 参数管理 """
    return render(request, 'params.html')


def message(request):
    """ 预约图书 """
    return render(request, 'message.html')


def main(request):
    """ 主界面-控制面板 """
    return render(request, 'main.html')


def cert(request):
    """ 图书入库 """
    return render(request, 'cert.html')


def auth_project(request):
    """ 项目审核 """
    return render(request, 'auth_project.html')


def auth_cert(request):
    """ 实名认证审核 """
    return render(request, 'auth_cert.html')


def auth_adv(request):
    """ 广告审核 """
    return render(request, 'auth_adv.html')


def advertisement(request):
    """ 查询书库 """
    return render(request, 'advertisement.html')
